package jun.home.dailycost.web;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import jun.home.dailycost.domain.Category;
import jun.home.dailycost.domain.Item;
import jun.home.dailycost.service.CategoryService;
import jun.home.dailycost.service.ItemService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping("/itemList")
public class ItemListController {
	
	@SuppressWarnings("deprecation")
	static Date DEFAULT_START = new Date(2012, 12, 24);
	static int DEFAULT_MONTH_DELTA = 1;
	
	@Autowired
	ItemService itemService;
	
	@Autowired
	CategoryService categoryService;
	
	List<Item> polulateItemList(Category cat, Date start, Date end) {
		if (cat != null) {
			return itemService.select(cat, start, end);
		} else {
			return itemService.select(start, end);
		}
	}
	
	List<Item> populateItemList(Category cat) {
		return itemService.selectByCategory(cat);
	}
	
	@RequestMapping(method = RequestMethod.GET)
	public String getItemList(
			@RequestParam(required = false, value="start") Date start,
			@RequestParam(required = false, value="end") Date end,
			@RequestParam(required = false, value="type") Integer cid,
			Model model) {
		Date s = null;
		Date e = null;
		Category cat = null;
		if (start != null || end != null) {
			if (start == null) {
				s = DEFAULT_START;
			} else {
				s = start;
			}
			if (end == null) {
				e = new Date();
			} else {
				e = end;
			}
		} else {
			// default to tracing back one month
			e = new Date(); 
			Calendar calendar = Calendar.getInstance();        
		    calendar.setTime(e);     
		    calendar.set(Calendar.MONTH,calendar.get(Calendar.MONTH) - DEFAULT_MONTH_DELTA);     
		    s = calendar.getTime();
		}
		if (cid != null) {
			cat = categoryService.selectById(cid);
		}
		List<Item> list = polulateItemList(cat, s, e);
		model.addAttribute("itemList", list);
		return "itemList";
	}

}
